#!/usr/bin/env python
#coding=utf-8

import time
from flask import Blueprint, session, request, render_template, make_response, g, url_for
from flask.ext.sqlalchemy import Pagination

from aladin.database import db
from aladin.helpers import toint, get_count, log_info, conver_model

from app.models.sys import SysCategory
from app.models.user import User, UserImage, UserRealnameApply
from app.models.follow import FollowCat
from app.models.teacher import Teacher, TeacherRegion

from app.services.yunpian import YunPian
from app.services.push import XingePushService


user = Blueprint('user', __name__)


@user.route('/')
@user.route('/<int:page>')
@user.route('/<int:page>-<int:page_size>')
def index(page=1, page_size=20):
    """用户列表"""
    g.title     = u'用户列表'
    g.page_type = 'search'

    args = request.args
    uid            = toint(args.get('uid', '0'))
    mobile         = args.get('mobile', '')
    teacher_status = toint(args.get('teacher_status', '0'))
    realname       = args.get('realname', '')

    q = User.query
    if uid > 0:
        q = q.filter(User.uid == uid)

    if mobile:
        q = q.filter(User.mobile == mobile)

    if realname:
        q = q.filter(User.realname == realname)

    if teacher_status > 0:
        q = q.filter(User.teacher_status == teacher_status)

    user_count = get_count(q)
    user_list = q.order_by(User.uid.desc()).offset((page-1)*page_size).\
                    limit(page_size).all()
    pagination  = Pagination(None, page, page_size, user_count, None)

    res = make_response(render_template('user/index.html', 
            user_list=user_list, pagination=pagination))
    res.set_cookie('goback_url', request.url)
    return res


@user.route('/detail/<int:uid>', methods=['GET', 'POST'])
def detail(uid):
    """用户详情"""
    g.title = u'用户详情'
    g.page_type = ''

    u = User.query.get_or_404(uid)

    if request.method == 'GET':
        follow_cat_list = FollowCat.query.filter(FollowCat.uid == uid).all()
        ui_list = UserImage.query.filter(UserImage.uid == uid).all()

        ura = UserRealnameApply.query.filter(UserRealnameApply.uid == uid).\
                order_by(UserRealnameApply.id.desc()).first()

        # 执教区域
        region_list = db.session.query(TeacherRegion.region_name).\
                        filter(TeacherRegion.uid == uid).all()
        tr_list = [tr.region_name for tr in region_list]
        region_names = u'、'.join(tr_list)

        return render_template('user/detail.html', user=u, 
            ui_list=ui_list, follow_cat_list=follow_cat_list,
            ura=ura, region_names=region_names)


@user.route('/image/delete/<int:id>')
def image_delte(id):
    """删除用户图片"""
    ui = UserImage.query.get(id)
    if ui is None:
        return u'找不到图片'

    is_delete = toint(request.args.get('is_delete', '0'))

    ui.is_delete = is_delete
    db.session.commit()

    return 'ok'


@user.route('/realname/')
@user.route('/realname/<int:page>')
@user.route('/realname/<int:page>-<int:page_size>')
def realname(page=1, page_size=20):
    """实名认证审核列表"""
    g.title     = u'实名认证审核列表'
    g.page_type = 'search'

    args = request.args
    uid    = toint(args.get('uid', '0'))
    status = toint(args.get('status', '0'))

    q = UserRealnameApply.query
    if uid > 0:
        q = q.filter(UserRealnameApply.uid == uid)

    if status > 0:
        q = q.filter(UserRealnameApply.status == status)

    apply_count = get_count(q)
    apply_list = q.order_by(UserRealnameApply.id.desc()).offset((page-1)*page_size).\
                    limit(page_size).all()
    pagination  = Pagination(None, page, page_size, apply_count, None)

    res = make_response(render_template('user/apply_list.html', 
            apply_list=apply_list, pagination=pagination))
    res.set_cookie('goback_url', request.url)
    return res


@user.route('/realname/apply')
def realname_apply():
    """实名认证审核"""
    args = request.args
    id = toint(args.get('id', '0'))
    status = toint(args.get('status', '0')) # 申请状态 0:默认 1:申请中 2:审核通过 3:拒绝通过
    reject_desc = args.get('reject_desc', '') # 拒绝原因

    if id <= 0 or status not in (2,3):
        return u'参数错误'

    ura = UserRealnameApply.query.get(id)
    if ura is None:
        return u'找不到申请信息'

    u = User.query.get(ura.uid)
    if u is None:
        return u'找不到用户信息'

    ura.status     = status
    ura.check_time = int(time.time())
    ura.checker    = session['admin_name']
    
    content = u'很抱歉的通知您，由于您的资料原因，实名认证审核没有通过，请重新申请。'
    if reject_desc:
        content = u'很抱歉的通知您，实名认证审核没有通过，原因：' + reject_desc

    if status == 2:
        content = u'恭喜您，您的实名认证申请，已经审核通过，感谢有您，有您才精彩。'
        u.is_real  = 1
        u.realname = ura.realname
        u.id_no    = ura.id_no
        u.teacher_status = 1 if u.teacher_status == 3 else u.teacher_status

        teacher = Teacher.query.get(u.uid)
        if teacher:
            teacher.is_real  = 1
            teacher.realname = ura.realname
            teacher.id_no    = ura.id_no

    elif status == 3 and u.teacher_status == 1:
        ui = UserImage.query.filter(UserImage.uid == u.uid).\
            filter(UserImage.type == 2).\
            filter(UserImage.status != 3).\
            filter(UserImage.id != id).\
            order_by(UserImage.id.desc()).first()
        if ui is None:
            u.teacher_status = 3

    db.session.commit()

    sms_content = content + u'【私享课】'
    sms = YunPian()
    res = sms.send_sms_text(u.mobile, sms_content)
    log_info(res)

    push = XingePushService()
    push.push_user(u.uid, u'私享课', content, {
            'trans_id':u.uid, 'trans_type':'me'})

    return 'ok'


@user.route('/cert/')
@user.route('/cert/<int:page>')
@user.route('/cert/<int:page>-<int:page_size>')
def cert(page=1, page_size=20):
    """证件照审核"""
    g.title     = u'证件照审核'
    g.page_type = 'search'

    args = request.args
    uid    = toint(args.get('uid', '0'))
    status = toint(args.get('status', '0'))

    q = db.session.query(UserImage.id, UserImage.uid, UserImage.img_original, 
            UserImage.add_time, UserImage.cherker, UserImage.status, 
            UserImage.check_time, SysCategory.cat_name)
    q = q.filter(UserImage.tid == SysCategory.cat_id).filter(SysCategory.cat_type == 1)

    q = q.filter(UserImage.type == 2)
    if uid > 0:
        q = q.filter(UserImage.uid == uid)

    if status > 0:
        q = q.filter(UserImage.status == status)

    img_count = get_count(q)
    img_list = q.order_by(UserImage.id.asc()).offset((page-1)*page_size).\
                    limit(page_size).all()
    pagination  = Pagination(None, page, page_size, img_count, None)

    res = make_response(render_template('user/cert.html', 
            img_list=img_list, pagination=pagination))
    res.set_cookie('goback_url', request.url)
    return res


@user.route('/cert/check')
def cert_check():
    """证书审核"""
    args = request.args
    id          = toint(args.get('id', '0'))
    status      = toint(args.get('status', '0')) # 申请状态 0:默认 1:申请中 2:审核通过 3:拒绝通过
    reject_desc = args.get('reject_desc', '')

    if id <= 0 or status not in (2,3):
        return u'参数错误'

    img = UserImage.query.get(id)
    if img is None:
        return u'找不到申请信息'

    uid = img.uid
    u = User.query.get(uid)
    if u is None:
        return u'找不到用户信息'

    ura = UserRealnameApply.query.filter(UserRealnameApply.uid == uid).\
                order_by(UserRealnameApply.id.desc()).first()

    img.status     = status
    img.check_time = int(time.time())
    img.checker    = session['admin_name']

    content = u'很抱歉通知您，您的资格证书审核没有通过，请重新提交审核。'
    if reject_desc:
        content += u'原因：' + reject_desc

    if status == 2:
        content = u'恭喜您，您的资格证书审核已经通过，感谢有您，有您才精彩。'
        u.is_cert = 1
        u.teacher_status = 1 if u.teacher_status == 3 else u.teacher_status
        teacher = Teacher.query.get(u.uid)
        if teacher:
            teacher.is_cert = 1

    elif status == 3 and u.teacher_status == 1:
        if ura is None or ura.status == 3:
            u.teacher_status = 3

    db.session.commit()

    sms_content = content + u'【私享课】'
    sms = YunPian()
    res = sms.send_sms_text(u.mobile, sms_content)
    log_info(res)

    push = XingePushService()
    push.push_user(u.uid, u'私享课', content, {
            'trans_id':u.uid, 'trans_type':'me'})

    return 'ok'


@user.route('/update_to_teacher')
def update_to_teacher():
    """升级成为老师"""
    args = request.args
    uid = toint(args.get('uid', '0'))
    status = toint(args.get('status', '0'))
    reject_desc = args.get('reject_desc', '')

    if uid <= 0:
        return u'uid小于0'

    if status not in (2,3):
        return u'状态错误'

    u = User.query.get(uid)
    if u is None:
        return u'找不到用户'

    if u.teacher_status == 2:
        return 'ok'

    content = u'很抱歉的通知您，由于您的资料原因，申请成为教练被拒，请重新申请。'
    if reject_desc:
        content = u'很抱歉的通知您，申请成为教练被拒，请重新申请。原因：' + reject_desc

    u.teacher_status = status
    if status == 2:
        content = u'恭喜您成为私享课认证导师，马上发布属于自己的私享课程吧。'

        teacher = conver_model(u, Teacher())
        teacher.goods_tags_json = ''
        teacher.is_display      = 1
        teacher.avatar          = u.avatar_big
        db.session.add(teacher)

        u.gid = 2

    db.session.commit()

    sms_content = content + u'【私享课】'
    sms = YunPian()
    res = sms.send_sms_text(u.mobile, sms_content)
    log_info(res)

    push = XingePushService()
    push.push_user(u.uid, u'私享课', content, {
            'trans_id':u.uid, 'trans_type':'me'})

    return 'ok'


